#include "aiqa_widget.h"
#include "ui_aiqa_widget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
#include <QScrollBar>
#include <QDateTime>
#include <QSpacerItem>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QSslConfiguration>
#include <QSsl>
#include <QFileInfo>
#include <QDir>

AiqaWidget::AiqaWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::AiqaWidget)
    , inputTextEdit(nullptr)
    , chatContainer(nullptr)
    , chatLayout(nullptr)
    , networkManager(new QNetworkAccessManager(this))
    , currentQuestion("")
    , thinkingTimer(new QTimer(this))
    , thinkingDotCount(0)
    , thinkingBubble(nullptr)
    , thinkingWidget(nullptr)
    , requestTimeoutTimer(new QTimer(this))
    , isDeepThinkMode(false)       // 初始化深度思考模式为关闭
    , referencedFiles()            // 初始化引用文件列表为空
{
    ui->setupUi(this);

    // 创建聊天显示区域
    chatContainer = new QWidget();
    chatLayout = new QVBoxLayout(chatContainer);
    chatLayout->setAlignment(Qt::AlignTop);
    chatLayout->setSpacing(10);
    chatLayout->setContentsMargins(10, 10, 10, 10);
    ui->scrollArea->setWidget(chatContainer);
    ui->scrollArea->setWidgetResizable(true);

    // 设置思考动画定时器
    thinkingTimer->setInterval(500);
    connect(thinkingTimer, &QTimer::timeout, this, &AiqaWidget::updateThinkingAnimation);

    // 设置请求超时定时器
    requestTimeoutTimer->setSingleShot(true);
    requestTimeoutTimer->setInterval(30000);
    connect(requestTimeoutTimer, &QTimer::timeout, this, &AiqaWidget::onRequestTimeout);

    // 创建输入框
    inputTextEdit = new QTextEdit(this);
    inputTextEdit->setMaximumHeight(60);
    inputTextEdit->setPlaceholderText("请输入您的问题...");

    // 重新布局底部区域
    QWidget *bottomWidget = ui->widget;
    QGridLayout *bottomLayout = qobject_cast<QGridLayout*>(bottomWidget->layout());
    if (bottomLayout) {
        QLayoutItem *labelItem = bottomLayout->itemAtPosition(0, 0);
        if (labelItem && labelItem->widget()) {
            bottomLayout->removeWidget(labelItem->widget());
            labelItem->widget()->deleteLater();
        }
        bottomLayout->addWidget(inputTextEdit, 0, 0, 1, 4);
    }

    // 连接按钮信号
    connect(ui->pushButton, &QPushButton::clicked, this, &AiqaWidget::onReferenceFileClicked);
    connect(ui->pushButton_2, &QPushButton::clicked, this, &AiqaWidget::onDeepThinkClicked);
    connect(ui->pushButton_3, &QPushButton::clicked, this, &AiqaWidget::onSendClicked);

    // 初始化深度思考按钮样式（普通状态）
    ui->pushButton_2->setStyleSheet(R"(
        QPushButton {
            background-color: #f0f0f0;
            color: #333333;
            border: 1px solid #cccccc;
            border-radius: 5px;
            padding: 5px 10px;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
        QPushButton:pressed {
            background-color: #d0d0d0;
        }
    )");

    // 添加欢迎消息
    addSystemMessage("欢迎使用AI问答系统！我已连接到GLM-4大模型，请输入您的问题开始对话。");
}

AiqaWidget::~AiqaWidget()
{
    delete ui;
}

void AiqaWidget::onSendClicked()
{
    QString question = inputTextEdit->toPlainText().trimmed();
    if (question.isEmpty()) return;

    addUserMessage(question);
    inputTextEdit->clear();
    processAIResponse(question);
}

void AiqaWidget::onReferenceFileClicked()
{
    // 打开文件选择对话框
    QStringList filePaths = QFileDialog::getOpenFileNames(
        this,
        "选择要引用的文件",
        QDir::homePath(),
        "所有文件 (*.*)"
    );

    if (filePaths.isEmpty()) {
        return;
    }

    // 添加选中的文件
    for (const QString &filePath : filePaths) {
        addFileReference(filePath);
    }

    // 更新文件引用显示
    updateFileReferencesDisplay();

    qDebug() << "引用文件:" << referencedFiles;
}

void AiqaWidget::onDeepThinkClicked()
{
    // 切换深度思考模式
    isDeepThinkMode = !isDeepThinkMode;

    if (isDeepThinkMode) {
        // 深度思考模式开启 - 浅蓝色背景，深蓝色文字
        ui->pushButton_2->setStyleSheet(R"(
            QPushButton {
                background-color: #b3d9ff;
                color: #0066cc;
                border: 1px solid #99ccff;
                border-radius: 5px;
                padding: 5px 10px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #a3c9ef;
            }
            QPushButton:pressed {
                background-color: #93b9df;
            }
        )");
        addSystemMessage("深度思考模式已激活，AI将进行更深入的推理分析。");
        qDebug() << "深度思考模式已开启";
    } else {
        // 深度思考模式关闭 - 恢复普通样式
        ui->pushButton_2->setStyleSheet(R"(
            QPushButton {
                background-color: #f0f0f0;
                color: #333333;
                border: 1px solid #cccccc;
                border-radius: 5px;
                padding: 5px 10px;
            }
            QPushButton:hover {
                background-color: #e0e0e0;
            }
            QPushButton:pressed {
                background-color: #d0d0d0;
            }
        )");
        addSystemMessage("深度思考模式已关闭。");
        qDebug() << "深度思考模式已关闭";
    }
}

void AiqaWidget::onRequestTimeout()
{
    qDebug() << "[Request Timeout] Request timed out after 30 seconds";
    addAiMessage("请求超时，请检查网络连接或稍后重试。");
    removeLoadingMessage();
}

void AiqaWidget::onAiResponseReceived(QNetworkReply *reply)
{
    qDebug() << "[AI Response] Processing response...";

    if (!reply) {
        qDebug() << "[AI Response] Reply is null!";
        return;
    }

    // 确保reply被正确释放
    reply->deleteLater();
    requestTimeoutTimer->stop();

    // 处理成功响应
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray responseBody = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(responseBody);
        qDebug() << "[AI Response] Raw Data:" << responseBody;

        if (doc.isObject()) {
            QJsonObject responseObj = doc.object();
            if (responseObj.contains("error")) {
                QString errorMsg = responseObj["error"].toObject()["message"].toString("未知错误");
                addAiMessage(QString("API错误：%1").arg(errorMsg));
                return;
            }
            if (responseObj.contains("choices") && responseObj["choices"].isArray()) {
                QJsonArray choices = responseObj["choices"].toArray();
                if (!choices.isEmpty()) {
                    QJsonObject choice = choices.first().toObject();
                    if (choice.contains("message") && choice["message"].isObject()) {
                        QString aiContent = choice["message"].toObject()["content"].toString().trimmed();
                        if (!aiContent.isEmpty()) {
                            addAiMessage(aiContent);
                            return;
                        }
                    }
                }
            }
            addAiMessage("抱歉，AI回复格式不正确，无法解析。");
            qDebug() << "[Response Parse Error] Invalid Format:" << responseBody;
        } else {
            addAiMessage("抱歉，AI回复不是合法的JSON格式。");
            qDebug() << "[Response Parse Error] Not JSON:" << responseBody;
        }
    } else {
        QString errorMsg = QString("网络请求失败：%1（错误码：%2）")
                          .arg(reply->errorString())
                          .arg(reply->error());
        addAiMessage(errorMsg);
        qDebug() << "[Response Error] HTTP Code:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    }
}

// 新增：添加文件引用
void AiqaWidget::addFileReference(const QString &filePath)
{
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists()) {
        QMessageBox::warning(this, "文件不存在", "选择的文件不存在：" + filePath);
        return;
    }

    if (fileInfo.size() > 10 * 1024 * 1024) { // 10MB限制
        QMessageBox::warning(this, "文件过大", "文件大小超过10MB限制：" + filePath);
        return;
    }

    // 避免重复添加
    if (!referencedFiles.contains(filePath)) {
        referencedFiles.append(filePath);
    }
}

// 新增：移除文件引用
void AiqaWidget::removeFileReference(int index)
{
    if (index >= 0 && index < referencedFiles.size()) {
        referencedFiles.removeAt(index);
        updateFileReferencesDisplay();
    }
}

// 新增：更新文件引用显示
void AiqaWidget::updateFileReferencesDisplay()
{
    // 移除现有的文件引用显示
    QLayoutItem *item;
    while ((item = chatLayout->takeAt(0)) != nullptr) {
        if (item->widget() && item->widget()->objectName() == "fileReference") {
            item->widget()->deleteLater();
            delete item;
        } else {
            // 如果不是文件引用组件，放回去
            chatLayout->addItem(item);
            break;
        }
    }

    // 添加新的文件引用显示
    if (!referencedFiles.isEmpty()) {
        QWidget *fileRefWidget = new QWidget();
        fileRefWidget->setObjectName("fileReference");
        QHBoxLayout *fileLayout = new QHBoxLayout(fileRefWidget);
        fileLayout->setContentsMargins(10, 5, 10, 5);

        QLabel *iconLabel = new QLabel();
        iconLabel->setText("📎");
        iconLabel->setStyleSheet("font-size: 14px;");

        QLabel *textLabel = new QLabel();
        textLabel->setText(QString("已引用 %1 个文件").arg(referencedFiles.size()));
        textLabel->setStyleSheet("color: #666666; font-size: 12px;");

        fileLayout->addWidget(iconLabel);
        fileLayout->addWidget(textLabel);
        fileLayout->addStretch();

        // 添加文件列表（可选显示）
        if (referencedFiles.size() <= 3) {
            for (int i = 0; i < referencedFiles.size(); ++i) {
                QLabel *fileLabel = new QLabel();
                QFileInfo fileInfo(referencedFiles[i]);
                fileLabel->setText(fileInfo.fileName());
                fileLabel->setStyleSheet(R"(
                    QLabel {
                        background-color: #e8f4fd;
                        border: 1px solid #b6d7f9;
                        border-radius: 3px;
                        padding: 2px 6px;
                        color: #0066cc;
                        font-size: 11px;
                        margin-left: 5px;
                    }
                )");
                fileLabel->setToolTip(referencedFiles[i]);
                fileLayout->addWidget(fileLabel);
            }
        }

        chatLayout->insertWidget(0, fileRefWidget);
    }
}

void AiqaWidget::addUserMessage(const QString &message)
{
    QWidget *messageWidget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout(messageWidget);
    layout->setContentsMargins(10, 5, 10, 5);
    layout->addStretch();

    QLabel *bubble = new QLabel();
    bubble->setWordWrap(true);
    bubble->setTextFormat(Qt::RichText);
    bubble->setTextInteractionFlags(Qt::TextSelectableByMouse);
    bubble->setStyleSheet(R"(
        QLabel {
            background-color: #95ec69;
            border-radius: 10px;
            padding: 10px;
            color: #000000;
            font-size: 14px;
            max-width: 400px;
        }
    )");

    QString timestamp = QDateTime::currentDateTime().toString("hh:mm");

    // 如果有引用文件，在消息中显示
    QString displayMessage = message;
    if (!referencedFiles.isEmpty()) {
        QString fileInfo = "\n\n📎 引用文件: ";
        for (const QString &filePath : referencedFiles) {
            QFileInfo fileInfoObj(filePath);
            fileInfo += fileInfoObj.fileName() + "; ";
        }
        fileInfo.chop(2); // 移除最后的逗号和空格
        displayMessage += fileInfo;
    }

    // 如果是深度思考模式，添加标记
    if (isDeepThinkMode) {
        displayMessage = "💭 深度思考模式\n" + displayMessage;
    }

    QString messageText = QString("%1<br><small style='color: #666;'>%2</small>")
                         .arg(displayMessage.toHtmlEscaped())
                         .arg(timestamp);
    bubble->setText(messageText);

    layout->addWidget(bubble);
    messageWidget->setLayout(layout);
    chatLayout->addWidget(messageWidget);

    // 自动滚动到底部
    QTimer::singleShot(50, [this]() {
        QScrollBar *scrollBar = ui->scrollArea->verticalScrollBar();
        scrollBar->setValue(scrollBar->maximum());
    });
}

void AiqaWidget::addAiMessage(const QString &message)
{
    removeLoadingMessage();

    QWidget *messageWidget = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout(messageWidget);
    layout->setContentsMargins(10, 5, 10, 5);

    QLabel *avatar = new QLabel();
    avatar->setFixedSize(30, 30);
    avatar->setStyleSheet(R"(
        QLabel {
            background-color: #0078d4;
            border-radius: 15px;
            color: white;
            font-weight: bold;
        }
    )");
    avatar->setAlignment(Qt::AlignCenter);
    avatar->setText("AI");

    QLabel *bubble = new QLabel();
    bubble->setWordWrap(true);
    bubble->setTextFormat(Qt::RichText);
    bubble->setTextInteractionFlags(Qt::TextSelectableByMouse);
    bubble->setStyleSheet(R"(
        QLabel {
            background-color: #f0f0f0;
            border-radius: 10px;
            padding: 10px;
            color: #333333;
            font-size: 14px;
            max-width: 400px;
        }
    )");

    QString timestamp = QDateTime::currentDateTime().toString("hh:mm");
    QString messageText = QString("%1<br><small style='color: #666;'>%2</small>")
                         .arg(message.toHtmlEscaped())
                         .arg(timestamp);
    bubble->setText(messageText);

    layout->addWidget(avatar);
    layout->addWidget(bubble);
    layout->addStretch();
    messageWidget->setLayout(layout);
    chatLayout->addWidget(messageWidget);

    // 自动滚动到底部
    QTimer::singleShot(50, [this]() {
        QScrollBar *scrollBar = ui->scrollArea->verticalScrollBar();
        scrollBar->setValue(scrollBar->maximum());
    });
}

void AiqaWidget::addSystemMessage(const QString &message)
{
    QLabel *systemLabel = new QLabel();
    systemLabel->setAlignment(Qt::AlignCenter);
    systemLabel->setStyleSheet(R"(
        QLabel {
            color: #999999;
            font-size: 12px;
            padding: 5px;
            background-color: #f8f8f8;
            border-radius: 5px;
        }
    )");
    systemLabel->setText(message);
    systemLabel->setMaximumWidth(300);

    QWidget *container = new QWidget();
    QHBoxLayout *containerLayout = new QHBoxLayout(container);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->addStretch();
    containerLayout->addWidget(systemLabel);
    containerLayout->addStretch();

    chatLayout->addWidget(container);
}

void AiqaWidget::addLoadingMessage()
{
    if (thinkingWidget) removeLoadingMessage();

    thinkingWidget = new QWidget();
    thinkingWidget->setObjectName("thinkingMessage");
    QHBoxLayout *layout = new QHBoxLayout(thinkingWidget);
    layout->setContentsMargins(10, 5, 10, 5);

    QLabel *avatar = new QLabel();
    avatar->setFixedSize(30, 30);
    avatar->setStyleSheet(R"(
        QLabel {
            background-color: #0078d4;
            border-radius: 15px;
            color: white;
            font-weight: bold;
        }
    )");
    avatar->setAlignment(Qt::AlignCenter);
    avatar->setText("AI");

    thinkingBubble = new QLabel();
    thinkingBubble->setWordWrap(true);
    thinkingBubble->setStyleSheet(R"(
        QLabel {
            background-color: #f0f0f0;
            border-radius: 10px;
            padding: 10px;
            color: #666666;
            font-size: 14px;
            font-style: italic;
            max-width: 400px;
        }
    )");
    thinkingDotCount = 0;

    // 根据模式显示不同的思考文本
    if (isDeepThinkMode) {
        thinkingBubble->setText("AI正在深度思考.");
    } else {
        thinkingBubble->setText("AI正在思考.");
    }

    layout->addWidget(avatar);
    layout->addWidget(thinkingBubble);
    layout->addStretch();
    thinkingWidget->setLayout(layout);
    chatLayout->addWidget(thinkingWidget);

    thinkingTimer->start();

    QTimer::singleShot(50, [this]() {
        QScrollBar *scrollBar = ui->scrollArea->verticalScrollBar();
        scrollBar->setValue(scrollBar->maximum());
    });
}

void AiqaWidget::removeLoadingMessage()
{
    thinkingTimer->stop();
    requestTimeoutTimer->stop();

    if (thinkingWidget) {
        chatLayout->removeWidget(thinkingWidget);
        thinkingWidget->deleteLater();
        thinkingWidget = nullptr;
        thinkingBubble = nullptr;
    } else {
        for (int i = 0; i < chatLayout->count(); ++i) {
            QLayoutItem *item = chatLayout->itemAt(i);
            if (item && item->widget() && item->widget()->objectName() == "thinkingMessage") {
                chatLayout->removeWidget(item->widget());
                item->widget()->deleteLater();
                break;
            }
        }
    }
}

void AiqaWidget::updateThinkingAnimation()
{
    if (!thinkingBubble) return;

    thinkingDotCount = (thinkingDotCount + 1) % 4;
    QString dots;
    for (int i = 0; i < thinkingDotCount; ++i) dots += ".";

    // 根据模式显示不同的思考文本
    if (isDeepThinkMode) {
        thinkingBubble->setText("AI正在深度思考" + dots);
    } else {
        thinkingBubble->setText("AI正在思考" + dots);
    }
}

void AiqaWidget::clearChat()
{
    thinkingTimer->stop();
    requestTimeoutTimer->stop();

    QLayoutItem *item;
    while ((item = chatLayout->takeAt(0)) != nullptr) {
        if (item->widget()) item->widget()->deleteLater();
        delete item;
    }

    thinkingWidget = nullptr;
    thinkingBubble = nullptr;

    // 清空引用文件
    referencedFiles.clear();
}

void AiqaWidget::processAIResponse(const QString &question)
{
    currentQuestion = question;
    addLoadingMessage();
    sendRequestToAI(question);
}

void AiqaWidget::sendRequestToAI(const QString &question)
{
    qDebug() << "[AI Request] Starting request...";

    // 构建JSON请求数据
    QJsonObject requestData;
    requestData["model"] = MODEL_NAME;
    QJsonArray messages;

    // 构建系统提示（根据模式调整）
    QString systemPrompt = "你是一个有帮助的AI助手。";
    if (isDeepThinkMode) {
        systemPrompt = "请进行深入思考和分析，提供详细、全面的回答。";
    }

    if (!referencedFiles.isEmpty()) {
        systemPrompt += " 用户提供了文件作为参考。";
    }

    QJsonObject systemMsg;
    systemMsg["role"] = "system";
    systemMsg["content"] = systemPrompt;
    messages.append(systemMsg);

    // 构建用户消息（包含引用文件信息）
    QString userMessage = question;
    if (!referencedFiles.isEmpty()) {
        userMessage += "\n\n我引用了以下文件作为参考：";
        for (const QString &filePath : referencedFiles) {
            QFileInfo fileInfo(filePath);
            userMessage += "\n- " + fileInfo.fileName();
        }
    }

    QJsonObject userMsg;
    userMsg["role"] = "user";
    userMsg["content"] = userMessage;
    messages.append(userMsg);

    requestData["messages"] = messages;
    requestData["stream"] = false;

    // 如果是深度思考模式，可以调整参数
    if (isDeepThinkMode) {
        requestData["temperature"] = 0.7;      // 稍微提高创造性
        requestData["max_tokens"] = 2000;      // 允许更长的回复
    }

    QJsonDocument doc(requestData);
    QByteArray requestBody = doc.toJson(QJsonDocument::Compact);
    qDebug() << "[AI Request] Data:" << requestBody;
    qDebug() << "[AI Request] API Key:" << API_KEY;
    qDebug() << "[AI Request] URL:" << API_URL;
    qDebug() << "[AI Request] Deep Think Mode:" << isDeepThinkMode;
    qDebug() << "[AI Request] Referenced Files:" << referencedFiles;

    // 配置网络请求
    QNetworkRequest request;
    request.setUrl(QUrl(API_URL));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", QString("Bearer %1").arg(API_KEY).toUtf8());
    request.setRawHeader("Accept", "application/json");
    request.setRawHeader("User-Agent", "AiqaWidget/1.0");

    // 配置SSL
    QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
    sslConfig.setProtocol(QSsl::TlsV1_2OrLater);
    sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
    request.setSslConfiguration(sslConfig);

    // 发送POST请求
    QNetworkReply *reply = networkManager->post(request, requestBody);

    // 启动超时定时器
    requestTimeoutTimer->start();

    // 使用lambda表达式连接finished信号，确保reply不为null
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        this->onAiResponseReceived(reply);
    });

    // 连接错误信号
    connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),
            this, [this, reply](QNetworkReply::NetworkError error) {
        requestTimeoutTimer->stop();
        qDebug() << "[Network Error] Code:" << error;
        qDebug() << "[Network Error] Msg:" << reply->errorString();

        QString errorMsg = QString("网络连接错误：%1").arg(reply->errorString());
        addAiMessage(errorMsg);
        removeLoadingMessage();
        reply->deleteLater();
    });

    qDebug() << "[AI Request] Request sent, waiting for response...";
}

void AiqaWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    QTimer::singleShot(100, [this]() {
        QScrollBar *scrollBar = ui->scrollArea->verticalScrollBar();
        scrollBar->setValue(scrollBar->maximum());
    });
}
